﻿(function (JFocus) {
    /**
    * 请求方式
    **/
    JFocus.type.URLRequestMethod = function () {
    };
    //GET方式
    JFocus.type.URLRequestMethod.GET = "GET";
    //POST方式
    JFocus.type.URLRequestMethod.POST = "POST";

    /**
    * URL请求类
    **/
    JFocus.type.URLRequest = function (url) {
        var _method = "GET";
        var _url = url;
        var _data = null;
        var _contentType = null;

        /**
        * 请求方式，有GET和POST
        **/
        this.method = function (value) {
            if (arguments.length > 0) {
                _method = value;
            } else {
                return _method;
            }
        };

        /**
        * 请求地址
        **/
        this.url = function (value) {
            if (arguments.length > 0) {
                _url = value;
            } else {
                return _url;
            }
        };

        /**
        * 请求数据
        **/
        this.data = function (value) {
            if (arguments.length > 0) {
                _data = value;
            } else {
                return _data;
            }
        };

        /**
        * 内容类型
        **/
        this.contentType = function (value) {
            if (arguments.length > 0) {
                _contentType = value;
            } else {
                return _contentType;
            }
        };
    };

    /**
    * 请求参数类
    **/
    JFocus.type.URLVariables = function (data) {
        var self = this;

        var _parseQueryString = function (queryString) {
            var qs = queryString.replace(/\+/g, ' ');
            var keyValueStringArray = qs.split("&");
            for (var i = 0; i < keyValueStringArray.length; i++) {
                var keyValuePair = keyValueStringArray[i].split("=");
                var key = decodeURIComponent(keyValuePair[0]);
                var value = keyValuePair.length == 2 ? decodeURIComponent(keyValuePair[1]) : key;
                self[key] = value;
            }
        };

        var _parseObject = function (obj) {
            for (var key in obj) {
                if (!(this[key] instanceof Function)) {
                    this[key] = obj[key];
                }
            }
        };

        if (typeof (data) == "string") {
            _parseQueryString(data);
        } else {
            _parseObject(data);
        }

        /**
        * 对象字符串描述
        **/
        this.toString = function () {
            var queryString = "";
            for (var key in this) {
                if (!(this[key] instanceof Function)) {
                    if (queryString == "") {
                        queryString = encodeURIComponent(key) + "=" + encodeURIComponent(this[key]);
                    } else {
                        queryString += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(this[key]);
                    }
                }
            }
            return queryString;
        };
    };

    /**
    * 请求加载器
    **/
    JFocus.type.URLLoader = function () {
        JFocus.type.EventDispatcher.apply(this, [this]);

        var self = this;

        var _handle = null;

        if (JFocus.browser.ie && JFocus.browser.checkVersion("ie", 7) == 0) {
            _handle = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                _handle = new ActiveXObject("Msxml2.XMLHttp");
            } catch (e) {
                try {
                    _handle = new ActiveXobject("Microsoft.XMLHttp");
                } catch (e) {
                }
            }
        } else if (window.XMLHttpRequest) {
            _handle = new XMLHttpRequest();
        }

        var _supportLevel2 = true;

        var _hasInit = false;
        var _hasCall = false;
        var _hasError = false;
        var _hasComplete = false;

        //进度事件
        var _progressHandler = function (event) {
            var e = new JFocus.type.ProgressEvent(JFocus.type.ProgressEvent.PROGRESS);
            e.loadedBytes = event.loaded;
            e.totalBytes = event.total;
            self.dispatchEvent(e);
        };

        //开始事件
        var _startHandler = function (event) {
            var e = new JFocus.type.Event(JFocus.type.Event.INIT);
            self.dispatchEvent(e);
        };

        //取消事件
        var _abortHandler = function (event) {
            var e = new JFocus.type.Event(JFocus.type.Event.CANCEL);
            self.dispatchEvent(e);
        };

        //错误事件
        var _errorHandler = function (event) {
            if (self.onError instanceof Function) {
                self.onError.apply(self, [null]);
            }

            var e = new JFocus.type.ErrorEvent(JFocus.type.ErrorEvent.ERROR);
            self.dispatchEvent(e);
        };

        //加载完成
        var _loadHandler = function (event) {
            if (self.onResult instanceof Function) {
                self.onResult.apply(self, [null]);
            }

            var e = new JFocus.type.Event(JFocus.type.Event.COMPLETE);
            self.dispatchEvent(e);
        };

        var _loadendHandler = function (event) {

        };

        var _readyStateChangeHandler = function (event) {
            var e;
            switch (_handle.readyState) {
                case 0:
                    //尚未初始化
                    break;
                case 1:
                    //已经打开连接
                    break;
                case 2:
                    //已经发出请求
                    if (!_hasInit) {
                        _hasLoad = true;
                        e = new JFocus.type.Event(JFocus.type.Event.INIT);
                        self.dispatchEvent(e);
                    }
                    break;
                case 3:
                    //进行交互接收数据
                    e = new JFocus.type.ProgressEvent(JFocus.type.ProgressEvent.PROGRESS);
                    self.dispatchEvent(e);
                    break;
                case 4:
                    //完成
                    _hasComplete = true;
                    if (_hasCall && !_hasError) {
                        if (self.onResult instanceof Function) {
                            self.onResult.apply(self, [null]);
                        }
                        //不发生异常的情况下派发完成事件
                        e = new JFocus.type.Event(JFocus.type.Event.COMPLETE);
                        self.dispatchEvent(e);
                    }
                    break;
            }
        };

        if (typeof _handle.withCredentials == "undefined") {
            //不支持XMLHttpRequest Level 2
            _supportLevel2 = false;
        }

        /**
        * 加载请求
        * @param request 请求对象
        **/
        this.load = function (request) {
            if (request != null && request instanceof JFocus.type.URLRequest) {
                _hasInit = false;
                _hasCall = false;
                _hasError = false;
                _hasComplete = false;

                var e;

                if (request.contentType() != null) {
                    _handle.overrideMimeType(request.contentType());
                }

                if (_supportLevel2) {
                    _handle.onprogress = _progressHandler;
                    _handle.onloadstart = _startHandler;
                    _handle.onabort = _abortHandler;
                    _handle.onerror = _errorHandler;
                    _handle.onload = _loadHandler;
                    _handle.onloadend = _loadendHandler;

                    try {
                        _handle.open(request.method(), request.url(), true);
                        if (request.data() != null) {
                            _handle.send(request.data().toString());
                        } else {
                            _handle.send("");
                        }
                    } catch (err) {

                        if (this.onError instanceof Function) {
                            this.onError.apply(this, [null]);
                        }

                        //派发事件
                        e = new JFocus.type.ErrorEvent(JFocus.type.ErrorEvent.ERROR);
                        e.message = err.message;
                        this.dispatchEvent(e);
                    }

                } else {
                    _handle.onreadystatechange = _readyStateChangeHandler;

                    try {
                        _handle.open(request.method(), request.url(), true);
                        if (request.data() != null) {
                            _handle.send(request.data().toString());
                        } else {
                            _handle.send("");
                        }
                    } catch (err) {
                        _hasError = true;

                        if (this.onError instanceof Function) {
                            this.onError.apply(this, [null]);
                        }

                        //派发事件
                        e = new JFocus.type.ErrorEvent(JFocus.type.ErrorEvent.ERROR);
                        e.message = err.message;
                        this.dispatchEvent(e);
                    }

                    _hasCall = true;
                    if (_hasComplete && !_hasError) {
                        if (this.onResult instanceof Function) {
                            this.onResult.apply(this, [null]);
                        }
                        //不发生异常的情况下派发完成事件
                        e = new JFocus.type.Event(JFocus.type.Event.COMPLETE);
                        self.dispatchEvent(e);
                    }
                }
            }
        };

        /**
        * 取消请求
        **/
        this.cancel = function () {
            _handle.abort();
        };

        /**
        * 回复数据
        **/
        this.data = function () {
            return _handle.responseText;
        };

        /**
        * 返回事件委托
        **/
        this.onResult = null;

        /**
        * 错误事件委托
        **/
        this.onError = null;
    };
    JFocus.inherited(JFocus.type.URLLoader, JFocus.type.EventDispatcher);

    /**
    * 发起一个HTTP服务请求
    * @param url 地址
    * @param data 提交数据，可以为字符串、对象、URLVariable
    * @param method 提交方式
    * @param contentType 内容类型
    * @param resultCallback 请求回复回调函数
    * @param errorCallback 请求错误回调函数
    * @return 返回URLLoader对象
    **/
    JFocus.httpService = function (url, data, method, contentType, resultCallback, errorCallback) {

        var request = new JFocus.type.URLRequest(url);
        request.method(method);
        request.contentType(contentType);
        if (data instanceof JFocus.type.URLVariables) {
            request.data(data);
        } else {
            request.data(new JFocus.type.URLVariables(data));
        }

        var loader = new JFocus.type.URLLoader();
        loader.onResult = resultCallback;
        loader.onError = errorCallback;
        loader.load(request);

        return loader;
    };
})(window.JFocus);